/**
 *  学习目标：Todos 案例
 */
import React from 'react'
import './styles/base.css'
import './styles/index.css'
import { Header } from './components/Header'
import { Main } from './components/Main'
import { Footer } from './components/Footer'
export default class App extends React.Component {
  state = {
    list: [
      { id: 1, content: '游戏', flag: true },
      { id: 2, content: '旅游', flag: false },
      { id: 3, content: '音乐', flag: true },
    ],
    type: 'all'

  }
  render() {
    return (
      <section className='todoapp'>
        {/* 头部 */}
        <Header listAdd={this.listAdd}></Header>
        {/* 主体 */}
        <Main list={this.state.list} allCheckFn={this.allCheckFn} remove={this.remove} check={this.check} type={this.state.type} ></Main>
        {/* 底部 */}
        <Footer list={this.state.list} ClearCompleted={this.ClearCompleted} type={this.state.type} listType={this.listType}></Footer>
      </section>
    )
  }
  remove = (id) => {
    let newArr = this.state.list.filter(item => item.id !== id)
    this.setState({
      list: newArr
    })
  }
  listAdd = (val) => {
    this.setState({
      list: [{ id: Date.now(), content: val, flag: false }, ...this.state.list]
    })
  }
  check = (id) => {
    let newArr = this.state.list.map(item => {
      if (item.id === id) {
        return {
          ...item,
          flag: !item.flag
        }
      } else {
        return item
      }
    })
    this.setState({
      list: newArr
    })
  }
  allCheckFn = (flag) => {
    console.log(flag);
    this.setState({
      list: this.state.list.map(item => {
        return { ...item, flag: !flag }
      })
    })

  }
  // 删除已完成
  ClearCompleted = () => {
    this.setState({
      list: this.state.list.filter(item => item.flag === false)
    })
  }
  listType = (type) => {
    this.setState({ type })
  }
  componentDidMount() {
    this.setState({
      list: JSON.parse(localStorage.getItem('todos')) || []
    })
  }
  componentDidUpdate() {
    localStorage.setItem('todos', JSON.stringify(this.state.list))
  }
}


